/* 
 * RTF is Based on an object by Simson Garfinkel and Michael Mahoney
 * in "NeXTSTEP Programming" published by Telos ISBN  0-387-97884-4
 */

#import "RTF.h"

const char *header =
	"{\\rtf0\\ansi{\\fonttbl\\f1\\fnil Times-Roman;\\f0\\fswiss"
	" Helvetica;}\\f0\n";
	
@implementation RTF

- init
{
	[super init];

	textStream = NXOpenMemory(0, 0, NX_READWRITE);
	NXWrite(textStream, header, strlen(header));
	return self;
}


- (NXStream *)stream
{
	NXSeek(textStream, 0L, NX_FROMSTART);
	return textStream;
}


/* appendRTF: appends an arbitrary RTF string
 * to the RTF object
 */
- appendRTF:(const char *)string
{
	NXSeek(textStream, 0L, NX_FROMEND);
	NXWrite(textStream, string, strlen(string));
	return self;
}


/* append: appends an ASCII text string, "escaping"
 * all of the special characters in the text.
 */
- append:(const char *)string
{
	if (string==0) return self; 									/* safety */

	NXSeek(textStream, 0L, NX_FROMEND);
	while(*string) {
		switch(*string) {
			/* escape special characters */
			case '\n':
			case '{':
			case '}':
			case '\\':
				NXPutc(textStream, '\\');
			break;
			default:
			break;
		}
		NXPutc(textStream, *string);
		string++;
	}
	return self;
}

- bold:(BOOL)flag
{
	[self appendRTF: flag ? "\\b " : "\\b0 "];
	return self;
}

- italic:(BOOL)flag
{
	[self appendRTF: flag ? "\\i " : "\\i0 "];
	return self;
}

- setJustify:(int)mode
{
	switch(mode) {
		case NX_LEFTALIGNED:
		case NX_JUSTIFIED:
			[self appendRTF: "\\ql "];
			break;
		case NX_CENTERED:
			[self appendRTF: "\\qc "];
			break;
	     case NX_RIGHTALIGNED:
			[self appendRTF: "\\qr "];
			break;
	}
	return self;
}

- tab
{
	[self appendRTF: "\\tab "];
	return self;
}

- setFontSize: (int) size
{
	char	buffer[256];
	
	sprintf(buffer, "\\fs%d", (size * 2) );
	[self appendRTF: buffer];

	return self;
}

- setLeftMargin: (int) marginInTwips;
{
	/* A twip is a typesetters measure. There are 1440 twips in
	 * an inch.
	 */
	char	buffer[256];
	
	sprintf(buffer, "\\margl%d", marginInTwips);
	[self appendRTF: buffer];
	
	return self;
}

- changeToTimes
{
	/* See the header above for definitions of families */
	[self appendRTF: "\\f1"];
	
	return self;
}

- changeToHelvetica
{
	/* See the header above for definitions of families */
	[self appendRTF: "\\f0"];
	
	return self;
}

- free
{
	NXCloseMemory(textStream, NX_FREEBUFFER);
	return [super free];
}

@end
